
// Implementation of a dictionary using an array and sequential search
// The array will be dynamically resized if necessary

#include <stdlib.h>
#include <string.h>

#include "array-dictionary.h"

#define SCALAR 2
#define init

// Constructor
ArrayDictionary::ArrayDictionary()
{
	// Add your code here
	maxNumber = 100;
	currentNumber = 0;
	array = (ArrayDictionaryNode*)malloc(maxNumber * sizeof(ArrayDictionaryNode));
	for (int idx = 0; idx < maxNumber; idx++) {
		array[idx].data = NULL;
		array[idx].key = NULL;
	}
}

// Add a record to the dictionary. Returns false if key already exists
bool
ArrayDictionary::addRecord( KeyType key, DataType record)
{
	for (int idx = 0; idx < currentNumber; idx++)		//Checks if the key is already in the dictionary, if so it returns false
		if (!strcmp(array[idx].key, key))
			return false;
	if (currentNumber == maxNumber-1) {		//Checks if the array is full, if so it increases the size by the scalar, which is defined as 2
		maxNumber *= SCALAR;
		array = (ArrayDictionaryNode*)realloc(array, maxNumber * sizeof(ArrayDictionaryNode));
	}
	array[currentNumber].key = strdup(key);
	array[currentNumber].data = record;
	currentNumber++;
	return true;
}

// Find a key in the dictionary and return corresponding record or NULL
DataType
ArrayDictionary::findRecord( KeyType key)
{
	for (int idx = 0; idx < currentNumber; idx++)
		if (!strcmp(array[idx].key, key))
			return array[idx].data;
	return NULL;
}

// Removes one element from the table
bool
ArrayDictionary::removeElement(KeyType key)
{
	for (int idx = 0; idx < currentNumber; idx++)
			if (!strcmp(array[idx].key, key)) {
				for (int jdx = idx; jdx < currentNumber-1; jdx++) {
					delete array[jdx].key;
					array[jdx].key = array[jdx+1].key;
					free(array[jdx].data);
					array[jdx].data = array[jdx+1].data;
				}
			}
	return true;

}

// Returns all the elements in the table as an array of strings.
// *n is the size of the table and it is returned by reference
KeyType *
ArrayDictionary::keys(int * n)
{
	KeyType *strings = (KeyType*)malloc(currentNumber * sizeof(KeyType));	//Allocates memory for the array of keys
	for (int idx = 0; idx < currentNumber; idx++)
		strings[idx] = strdup(array[idx].key);
	*n = currentNumber;
	return strings;
}
